package com.example.demo.factory;

import com.example.demo.factory.annoation.Processor;
import com.example.demo.factory.service.ProcessHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 工厂类，spring容器初始化后注入实例到内存中
 *
 * @author mdl
 * @date 2020/4/2 11:08
 */
@Service
public class ProcessorFactory {

    private final Map<String, ProcessHandle> processHandleHashMap = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        // 根据注解类型获取所有实现的实例
        Map<String, ProcessHandle> processHandleBeans = applicationContext.getBeansOfType(ProcessHandle.class);
        for (ProcessHandle processHandle : processHandleBeans.values()) {
            if (processHandle.getClass().isAnnotationPresent(Processor.class)) {
                Processor processorAnnotation = processHandle.getClass().getAnnotation(Processor.class);
                processHandleHashMap.put(processorAnnotation.value().getValue(), processHandle);

            }
        }
    }

    public ProcessHandle getProcessHandleByKey(String operate) {
        return processHandleHashMap.get(operate);
    }
}
